package crypt

import (
	"encoding/base64"
	"encoding/hex"
	"io"
)

const (
	Padding = byte(58)
)

func DealLength(bs []byte, length int) []byte {
	beforeLength := len(bs)
	if beforeLength > length {
		bs = bs[:length]
	} else if beforeLength < length {
		for i := 0; i < length-beforeLength; i++ {
			bs = append(bs, Padding)
		}
	}
	return bs
}

type ICrypt interface {
	io.Writer
	Sum(b []byte) []byte
}

type Crypt struct {
	ICrypt
}

func New(i ICrypt) *Crypt {
	return &Crypt{
		ICrypt: i,
	}
}

func (this *Crypt) Encrypt(bs []byte) []byte {
	this.Write(bs)
	return this.Sum(nil)
}

func (this *Crypt) EncryptBytes(s string) []byte {
	return this.Encrypt([]byte(s))
}

func (this *Crypt) EncryptHex(s string) string {
	return hex.EncodeToString(this.Encrypt([]byte(s)))
}

func (this *Crypt) EncryptStr(s string) string {
	return string(this.Encrypt([]byte(s)))
}

func (this *Crypt) EncryptBase64(s string) string {
	return base64.StdEncoding.EncodeToString(this.Encrypt([]byte(s)))
}

func (this *Crypt) EncryptHexBase64(s string) string {
	return base64.StdEncoding.EncodeToString([]byte(hex.EncodeToString(this.Encrypt([]byte(s)))))
}
